//
//  SolutionParser.m
//  PentahoIConsole
//
//  Created by Bill Seyler on 6/10/10.
//  Copyright 2010 Pentaho Corporation. All rights reserved.
//

#import "SolutionParser.h"
#import "PentahoIPPUCAppDelegate.h"
#import "SolutionNode.h"

#define kRepositoryTag @"repository"
#define kFileTag @"file"

#define kPathTag @"path"
#define kNameTag @"name"
#define kLocalizedNameTag @"localized-name"
#define kDescriptionTag @"description"
#define kUrlTag @"url"
#define kParamterServiceURLTag @"param-service-url"
#define kIsDirectoryTag @"isDirectory"
#define kVisibleTag @"visible"


@implementation SolutionParser
@synthesize appDelegate;

@synthesize currentNode;
@synthesize rootNode;

- (id)init {
	[super init];
	
	appDelegate = (PentahoIPPUCAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
	attributes:(NSDictionary *)attributeDict
{	
	SolutionNode *newNode = [[SolutionNode alloc] init];

	if ([elementName isEqualToString:kRepositoryTag]) {
		[self setRootNode:newNode];
		[self setCurrentNode:rootNode];
	} else if ([elementName isEqualToString:kFileTag]) {
		[newNode setParent:[self currentNode]];
		[self setCurrentNode:newNode];
		[[[currentNode parent] children] addObject:currentNode];
	}
	[currentNode setRepository_path:[attributeDict objectForKey:kPathTag]];
	[currentNode setFileName:[attributeDict objectForKey:kNameTag]];
	[currentNode setLocalized_name:[attributeDict objectForKey:kLocalizedNameTag]];
	[currentNode setDescription:[attributeDict objectForKey:kDescriptionTag]];
	[currentNode setUrl:[attributeDict objectForKey:kUrlTag]];
	[currentNode setParameter_service_url:[attributeDict objectForKey:kParamterServiceURLTag]];
	[currentNode setDirectory:[[attributeDict objectForKey:kIsDirectoryTag] boolValue]];
	[currentNode setVisible:[[attributeDict objectForKey:kVisibleTag] boolValue]];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
	if ([elementName isEqualToString:kRepositoryTag]) {
	} else if ([elementName isEqualToString:kFileTag]) {
		[self setCurrentNode:[currentNode parent]];
	}	
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
	[self removeInvisibleNodes:rootNode];
}

- (void)removeInvisibleNodes:(SolutionNode *)node
{
	NSMutableArray *deleteArray = [[NSMutableArray alloc] init];
	
	for (SolutionNode* childNode in [node children]) {
		[self removeInvisibleNodes:childNode];
		if (![childNode visible]) {
			[deleteArray addObject:childNode];
		}
	}
	
	for (SolutionNode* childNode in deleteArray) {
		[node removeChild:childNode];
	}
	
	[deleteArray release];
}

@end
